<template>
	<view>
		<u-sticky>
			<view class="header" id="header">
				<u-navbar :title="'每月报表'"  bgColor="transparent" :titleStyle="'color: white'"
					:leftIconColor="'white'" placeholder="true" autoBack />
					
				<view class="filter-criteria-box">
					<view class="filter-criteria" @click="showSelectStore()">
						<view v-if="selectMchStoreId == -1">
							全部场地（{{totalMerchantStore}}个）
						</view>
						<view v-else>
							{{selectMchStoreName}}
						</view>
						<u-icon name="arrow-down-fill" color="#FFFFFF" size="12"></u-icon>
					</view>
					<view class="filter-criteria">
						<view class="filter-criteria-item" @click="showDateTimePickerStart">
							<view>
								{{startDateStr}}
							</view>
							<u-icon name="arrow-down-fill" color="#FFFFFF" size="12"></u-icon>
						</view>
						~
						<view class="filter-criteria-item" @click="showDateTimePickerEnd">
							<view>
								{{endDateStr}}
							</view>
							<u-icon name="arrow-down-fill" color="#FFFFFF" size="12"></u-icon>
						</view>
					</view>
				</view>
			</view>
		</u-sticky>
		<view class="content">
			<view class="line">
				<view class="line-title">
					每月营业额
				</view>
				<view style="width:100%;height:400rpx;">
					<echarts ref="lineChart" :option="line" canvasId="lineChart"></echarts>
				</view>
			</view>
			<view :style="'height:'+(height - tabBarHeight)+'px'">
				<!-- API链接: https://ext.dcloud.net.cn/plugin?id=7511 -->
				<zb-table
					:fit="true"
				    :columns="column"
				    :stripe="true"
				    :border="false"
				    :data="statsStoreList"></zb-table>
			</view>
		</view>
		<u-picker :show="selectStoreShow" :closeOnClickOverlay="true" @close="closeSelectStore()"
			@confirm="selectStoreConfirm" @cancel="closeSelectStore()" :columns="merchantStoreVoColumns"
			keyName="storeName"></u-picker>
		<u-datetime-picker
				:show="startShowTime"
				v-model="startTime"
				:minDate="timesTempMin"
				:maxDate="timesTempMax"
				mode="year-month"
				:formatter="formatter"
				@confirm="confirmDateTimePickerStart"
				@cancel="hideDateTimePickerStart"
				@close="hideDateTimePickerStart"
				ref="datetimePickerStart"
		></u-datetime-picker>
		<u-datetime-picker
				:show="endShowTime"
				v-model="endTime"
				:minDate="timesTempMin"
				:maxDate="timesTempMax"
				mode="year-month"
				:formatter="formatter"
				@confirm="confirmDateTimePickerEnd"
				@cancel="hideDateTimePickerEnd"
				@close="hideDateTimePickerEnd"
				ref="datetimePickerEnd"
		></u-datetime-picker>
	</view>
</template>

<script>
	import echarts from '@/pages-other/operation-stats/echarts-uniapp/echarts-uniapp.vue'
	export default {
		components: {
			echarts
		},
		props: {
			// 底部导航栏高度
			tabBarHeight: {
				type: Number,
				default: 0
			}
		},
		data() {
			return {
				selectMchStoreId: -1,
				selectMchStoreName: '',
				//全部场地
				totalMerchantStore: 0,
				
				selectStoreShow: false,
				
				merchantStoreVoColumns: [],
				statsStoreList: [], // 统计集合
				
				startShowTime: false,
				endShowTime: false,
				
				// showTime: false,
				startTime: '',
				endTime: '',
				startDateStr: '',
				endDateStr: '',
				
				timesTempMin: '',
				timesTempMax: '',
					
				line: {},
				
				height: 0,
				column:[
				  { name: 'dateStr', label: '日期',fixed:true,align:'center'},
				  { name: 'orderCount', label: '订单数',align:'center'},
				  { name: 'quantityOfCoinsSold', label: '售币数量',align:'center'},
				  { name: 'giftConsume', label: '出礼数',align:'center'},
				  { name: 'giftCost', label: '出礼成本',align:'center'},
				  { name: 'turnover', label: '总金额',align:'center'},
				],
			}
		},
		methods: {
			// 用这个,因为是组件
			Load(){
				let endLastMoth = new Date(this.$date.getTime().endLastMonth);
				let startThisYear = new Date(this.$date.getTime().startThisYear);
				startThisYear.setHours(0);
				startThisYear.setMinutes(0);
				startThisYear.setSeconds(0);
				console.log(startThisYear)
				console.log(this.$date.getTime().startThisYear)
				if((endLastMoth.getMonth() + 1) == 12){
					// 如果上个月是12月的话就查上一年的
					startThisYear.setFullYear(startThisYear.getFullYear() - 1);
				}else if((endLastMoth.getMonth() + 1) == 1){
					// 如果上一个月是1月的话
					startThisYear.setFullYear(endLastMoth.getFullYear() - 1);
				}
				this.startTime = Number(startThisYear);
				this.endTime = Number(endLastMoth)
				
				this.startDateStr = this.$date.dateFormatYM2(this.startTime);
				this.endDateStr = this.$date.dateFormatYM2(this.endTime);
				this.findStoreList();
				this.findData();
			},
			Ready(){
				this.timesTempMin = Number(new Date().setFullYear((new Date().getFullYear() - 2)))
				this.timesTempMax = this.endTime;
				this.$refs.datetimePickerStart.setFormatter(this.formatter)
				this.$refs.datetimePickerEnd.setFormatter(this.formatter)
				
				this.getPomHeight();
			},
			
			PullDownRefresh(){
				this.findStoreList();
				this.findData();
			},
			
			closeSelectStore() {
				this.selectStoreShow = false;
			},
			showSelectStore() {
				this.selectStoreShow = true;
			},
			selectStoreConfirm(e) {
				this.selectMchStoreId = e.value[0].id;
				this.selectMchStoreName = e.value[0].storeName
				this.findData();
				this.closeSelectStore();
			},
			findStoreList(){
				this.$api('merchantStore.findMerchantStoreIdByUserId').then(res => {
					if(res.status == 0){
						if(res.data){
							this.totalMerchantStore = res.data.length;
						}
						let merchantStoreColums = [];
						let all = {
							id: -1,
							storeName: '全部场地'
						}
						merchantStoreColums.push(all);
						this.merchantStoreVoColumns = [];
						this.merchantStoreVoColumns.push([...merchantStoreColums,...res.data]);
					}else{
						this.$helpers.toast("请求数据失败:"+res.msg);
					}
				}).catch(e => {
					console.log(e);
					this.$helpers.toast('场地查询失败，服务器访问失败');
				})
			},
			
			findData(){
				let params = {
					mchStoreId: this.selectMchStoreId,
					startDateStr: this.startDateStr,
					endDateStr: this.endDateStr,
					type: 2
				}
				this.$api('statsStore.findStoreStatsStateList',params).then(res => {
					if(res.status == 0){
						this.statsStoreList = res.data;
						let line = this.initEcharts();
						let xAxisData = [];
						let seriesData = [];
						let monthList = this.$date.getMonthsBetween(this.startDateStr,this.endDateStr);
						console.log(monthList,"mothList");
						monthList.forEach(item => {
							let date = new Date(item);
							xAxisData.push((date.getMonth() + 1) + '月');
							let turnover = 0;
							this.statsStoreList.forEach(item2 => {
								if(item2.dateStr == item){
									turnover = item2.turnover;
								}
							})
							seriesData.push(turnover);
						})
						line.xAxis.data = xAxisData;
						line.series[0].data = seriesData;
						console.log("数据,",line.series[0].data)
						this.line = line;
						// zb-table插件的格式化参数有问题会导致出现省略号，所以这里循环一次自己给参数
						res.data.forEach(item => {
							item['dateStr'] = this.$u.timeFormat(Date.parse(item.dateStr),'yy年mm月');
							item['giftCost'] = "￥"+item['giftCost'];
							item['turnover'] = "￥"+item['turnover'];
						})
						uni.stopPullDownRefresh();
					}else{ 
						this.$helpers.toast("请求数据失败:"+res.msg);
						uni.stopPullDownRefresh();
					}
				}).catch(e => {
					console.log(e);
					this.$helpers.toast('场地查询失败，服务器访问失败');
					uni.stopPullDownRefresh();
				})
			},
			
			lineInit(e) {
				let {
					width,
					height
				} = e;
				console.log(e)
				let canvas = this.$refs.lineChart.canvas
				echarts.setCanvasCreator(() => canvas);
				let lineChart = echarts.init(canvas, null, {
					width: width,
					height: height
				})
				canvas.setChart(lineChart) 
				lineChart.setOption(this.line)
				this.$refs.lineChart.setChart(lineChart)
			},
			formatter(type, value) {
				if (type === 'year') {
					return `${value}年`
				}
				if (type === 'month') {
					return `${value}月`
				}
				return value
			},
			// 显示开始时间弹窗
			showDateTimePickerStart(){
				this.startShowTime = true;
			},
			// 隐藏开始时间弹窗
			hideDateTimePickerStart(){
				this.startShowTime = false;
			},
			// 显示结束时间弹窗
			showDateTimePickerEnd(){
				this.endShowTime = true;
			},
			// 隐藏结束时间弹窗
			hideDateTimePickerEnd(){
				this.endShowTime = false;
			},
			// 开始时间弹窗点击确定
			confirmDateTimePickerStart(e){
				console.log(e);
				if(Number(e.value) > Number(this.endTime)){
					this.$helpers.toast("开始时间需早于结束时间");
					return;
				}
				this.startTime = e.value;
				this.startDateStr = this.$date.dateFormatYM2(this.startTime);
				this.findData();
				this.hideDateTimePickerStart();
			},
			// 结束时间点击确定
			confirmDateTimePickerEnd(e){
				console.log(e);
				if(Number(e.value) < Number(this.startTime)){
					this.$helpers.toast("开始时间需早于结束时间");
					return;
				}
				this.endTime = e.value;
				this.endDateStr = this.$date.dateFormatYM2(this.endTime);
				this.findData();
				this.hideDateTimePickerEnd();
			},
			
			initEcharts(){
				return {
					legend: {
						data: ['订单笔数']
					},
					xAxis: {
						type: 'category',
						data: [],
						axisLabel: {
							textStyle: { //底下文字样式
								fontSize: 10,
								color: 'rgb(132,132,132)'
							}
						},
						axisLine: { //设置左边竖线边框样式
							lineStyle: {
								color: 'rgb(160,160,160)',
								width: 1,
								type: 'solid',
							},
						}
					},
					yAxis: {
						type: 'value',
						data: [],
						splitLine: { //网格线
							lineStyle: {
								type: 'dashed' //设置网格线类型 dotted：虚线   solid:实线
							},
							show: true //隐藏或显示
						},
						axisLine: { //设置左边竖线边框样式
							lineStyle: {
								color: 'rgb(160,160,160)',
								width: 0,
								type: 'none',
							},
						}
					},
					grid: {
				     //距离上下左右的距离
						left: 30,
						right: 30,
						bottom: 30,
						top: 30,
						containLabel: true
					},
					series: [{
				
						symbolSize: 0,
						data: [],
						type: 'line',
						color: ['#399EFD'], //折线条的颜色
						smooth: true ,//是否变成圆润的折线
						areaStyle: {
							color: '#EFF7FF'
						},
					}]
				}
			},
			//计算高度
			getPomHeight() {
				let query = wx.createSelectorQuery().in(this)
				query.select('#header').boundingClientRect()
				query.exec(res => {
					let windowHeight = wx.getSystemInfoSync().windowHeight
					this.height = windowHeight
					for (let i = 0; i < res.length; i++) {
						this.height -= res[i].height;
					}
				})
			},
		}
	}
</script>

<style lang="scss" scoped>
	.header{
		background-color: #6072FF;
		
		.filter-criteria-box {
			display: flex;
			// margin-top: 50rpx;
			// padding: 0 80rpx;
			justify-content: space-between;
			color: #FFFFFF;
			font-size: 26rpx;
			font-weight: 700;
		
			.filter-criteria {
				flex: 1;
				display: flex;
				align-items: center;
				justify-content: center;
				padding: 30rpx 0;
				
				.filter-criteria-item{
					flex: 1;
					display: flex;
					align-items: center;
					justify-content: center;
				}
			}
		}
		.table-th-box{
			// position: absolute;
			padding: 0 24rpx;
			background-color: white;
			.table-th{
				width: 100%;
				display: table-row;
				.table-item{
					width: 140rpx;
					text-align: center;
					padding: 12px 10px;
					display: table-cell;
					box-sizing: border-box;
					font-size: 14px;
					font-weight: bold;
					color: #909399;
					border-bottom: 1px #ebeef5 solid;
				}
			}
		}
	}
	.content{
		background-color: white;
		.line {
			border-radius: 20rpx;
			background: $uni-bg-color;
			margin-bottom: 20rpx;
			
			.line-title{
				color: rgb(13, 13, 13);
				font-size: 32rpx;
				padding: 30rpx;
				padding-bottom: 0;
			}
		}
		
		/deep/ .odd{
			background-color: #F6F9FF !important;
		}
		/deep/ .item-th{
			background-color: rgb(239, 240, 242) !important;
		}
		/deep/ .item-td{
			width: fit-content !important;
			border-bottom: none !important;
		}
	}
</style>
